package cn.huixh.blindbox.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author huixh
 * @version 1.0
 * @date 2022/5/7 14:05
 */
@Configuration
@EnableTransactionManagement
@Import(cn.hutool.extra.spring.SpringUtil.class)
public class MybatisPlusConfig {
    /**
     * 去除Warning
     */
    private static void disableWarning() {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            Unsafe u = (Unsafe) theUnsafe.get(null);
            Class< ? > cls = Class.forName("jdk.internal.module.IllegalAccessLogger");
            Field logger = cls.getDeclaredField("logger");
            u.putObjectVolatile(cls, u.staticFieldOffset(logger), null);
        } catch ( Exception ignored ) {
        }
    }

    /**
     * 分页插件
     *
     * @return PaginationInnerInterceptor
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 防止全表更新与删除
     */
    @Bean
    public MybatisPlusInterceptor blockAttackInnerInterceptor() {
        /*去除警告，目前暂时无影响，持续关注*/
        disableWarning();
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        /*针对 update 和 delete 语句*/
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        return interceptor;
    }
}
